package com.wechat.controller;


import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName WX
 * @Author daxuexiu
 * @Date 2019/1/8 16:23
 **/
@Controller
public class WX {
    public  String URL[] = {

    };
    //public  final String APP_ID = "wx5b071c96890326ee";                     //公司Id
    //public  final String APP_SECRET = "a5b51bdb3aa4fa7b81d8132175d512a3";   //公司a5b51bdb3aa4fa7b81d8132175d512a3

    public  final String APP_ID = "wxef2bc7deed36d1b7";                     //公司Id
    public  final String APP_SECRET = "6bbcd1bc458129a4c525fe6969a2d5ae";   //公司a5b51bdb3aa4fa7b81d8132175d512a3

    public  String getAccessToken() {
        String access_token = "";
        String grant_type = "client_credential";//获取access_token填写client_credential
        String AppId = APP_ID;//第三方用户唯一凭证
        String secret = APP_SECRET;//第三方用户唯一凭证密钥，即appsecret
        //这个url链接地址和参数皆不能变
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + AppId + "&secret=" + secret;

        try {
            java.net.URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = new JSONObject(message);
            System.out.println("getAccessToken JSON字符串：" + demoJson);
            access_token = demoJson.getString("access_token");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return access_token;
    }

    public  String getTicket(String access_token) {
        String ticket = null;
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";//这个url链接和参数不能变
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = new JSONObject(message);
            System.out.println("getTicket JSON字符串：" + demoJson);
            ticket = demoJson.getString("ticket");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }

    public  String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping("/wwwechat")
    public String getSignature(Model model) {
//        if (args == null || args.length < 1) return;
        //1、获取AccessToken
        String accessToken = getAccessToken();

        //2、获取Ticket
        String jsapi_ticket = getTicket(accessToken);

        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

        System.out.println("accessToken:" + accessToken + "\njsapi_ticket:" + jsapi_ticket + "\n时间戳：" + timestamp + "\n随机字符串：" + noncestr);


        String url = "http://daxuexiu.mynatapp.cc/wwwechat";
        System.out.print("\nStart To url:" + url + "\n");

        //4、获取url
        //            String url = "http://www.luiyang.com/add.html";
            /*根据JSSDK上面的规则进行计算，这里比较简单，我就手动写啦
            String[] ArrTmp = {"jsapi_ticket","timestamp","nonce","url"};
            Arrays.sort(ArrTmp);
            StringBuffer sf = new StringBuffer();
            for(int i=0;i<ArrTmp.length;i++){
                sf.append(ArrTmp[i]);
            }
    */

        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;

        //6、将字符串进行sha1加密
        String signature = SHA1(str);
        System.out.print("{\"signature\":\"" + signature + "\",\"noncestr\":\"" + noncestr + "\",\"timestamp\":" + timestamp + "}");
//        System.out.println("参数：" + str + "\n签名：" + signature);

        model.addAttribute("signature",signature);
        model.addAttribute("noncestr",noncestr);
        model.addAttribute("timestamp",timestamp);
        return "wechat";

    }


    @RequestMapping(value = "/showWechat",method = RequestMethod.GET)
    public String showWechat(){
        return "wechat";
    }

    @RequestMapping(value = "/share",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> share(HttpServletRequest request,HttpServletResponse response) {
//        if (args == null || args.length < 1) return;
        //1、获取AccessToken
        String accessToken = getAccessToken();

        //2、获取Ticket
        String jsapi_ticket = getTicket(accessToken);

        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

        System.out.println("accessToken:" + accessToken + "\njsapi_ticket:" + jsapi_ticket + "\n时间戳：" + timestamp + "\n随机字符串：" + noncestr);


        String url = request.getParameter("url");
        System.out.print("\nStart To url:" + url + "\n");

        //4、获取url
        //            String url = "http://www.luiyang.com/add.html";
            /*根据JSSDK上面的规则进行计算，这里比较简单，我就手动写啦
            String[] ArrTmp = {"jsapi_ticket","timestamp","nonce","url"};
            Arrays.sort(ArrTmp);
            StringBuffer sf = new StringBuffer();
            for(int i=0;i<ArrTmp.length;i++){
                sf.append(ArrTmp[i]);
            }
    */

        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;

        //6、将字符串进行sha1加密
        String signature = SHA1(str);
        System.out.print("{\"signature\":\"" + signature + "\",\"noncestr\":\"" + noncestr + "\",\"timestamp\":" + timestamp + "}");
//        System.out.println("参数：" + str + "\n签名：" + signature);

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("signature",signature);
        map.put("noncestr",noncestr);
        map.put("timestamp",timestamp);

        return map;

    }
}
